package com.superteam.zzl.view;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

//import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapView;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.superteam.zzl.activity.MainActivity;
import com.superteam.zzl.activity.R;
import com.superteam.zzl.activity.RecommandActivity.Banner1Activity;
import com.superteam.zzl.activity.SearchActivity;
import com.superteam.zzl.activity.databinding.RecommendfragmentItemTopBinding;
import com.superteam.zzl.activity.databinding.RecommendfragmentItemTopLocalBinding;
import com.superteam.zzl.activity.databinding.RecommendfragmentItemTopRecBinding;
import com.superteam.zzl.activity.databinding.RecommendfragmentLayoutBinding;
import com.superteam.zzl.adapter.RecommendFragmentAdapter.GvCityAdapter;
import com.superteam.zzl.adapter.RecommendFragmentAdapter.HistoryAdapter;
import com.superteam.zzl.adapter.RecommendFragmentAdapter.LvLocalAdapter;
import com.superteam.zzl.adapter.RecommendFragmentAdapter.LvRecAdapter;
import com.superteam.zzl.cans.ContentURLs;
import com.superteam.zzl.gen.HistoryDao;
import com.superteam.zzl.model.RecommendFragment.History;
import com.superteam.zzl.model.RecommendFragment.MainData;
import com.superteam.zzl.utils.BaiDuMapUtils;
import com.superteam.zzl.utils.GreenDaoManager;
import com.superteam.zzl.utils.ImageCarousel;
import com.superteam.zzl.utils.ListViewUtils;
import com.superteam.zzl.utils.ScreenUtils;
import com.superteam.zzl.viewmodel.RecommendFragment.Data;
import com.superteam.zzl.viewmodel.RecommendFragment.ListData;
import com.superteam.zzl.widget.RecommandGridView;
import com.superteam.zzl.widget.RecommandListView;

import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.superteam.zzl.activity.R;
import com.superteam.zzl.activity.databinding.RecommendfragmentLayoutBinding;
import com.superteam.zzl.utils.ImageCarousel;


import java.util.ArrayList;

/**
 * Created by zhang on 2017/1/6.
 * 推荐
 */

public class MainRecommendFragment extends BaseFragment implements OnItemClickListener{

    private ConvenientBanner mCb;//图片轮播控件对象
    private ImageCarousel imageCarousel;//图片轮播类对象
    private ArrayList<Bitmap> bitmaps;//轮播图片集合
    private RecommendfragmentLayoutBinding rfl;//DataBinding产生的对应的碎片对象
    private ListData data;//数据源对象
    private Data mData;
    private ScrollView sc;
    private RecommandListView lv_rec,lv_local;
    private RecommandGridView gv;
    private GvCityAdapter gvAdapter;
    private LvLocalAdapter lvLocalAdapter;
    private LvRecAdapter lvRecAdapter;
    private ArrayList<MainData.ItemsBean.ItemListBean> items;
    private ArrayList<MainData.HolidayBeanX.HolidayBean> holidays;
    private ArrayList<MainData.ZhuangtiBean> zhuangtis;
    private RecommendfragmentItemTopBinding itemTopBinding;
    private RecommendfragmentItemTopLocalBinding itemTopLocalBinding;
    private RecommendfragmentItemTopRecBinding itemTopRecBinding;
    //private TextView tv_1,tv_2,tv_3,tv_4,tv_5,tv_6;
    private Intent intent;
    private String [] arr;
    private LinearLayout ly;
    private MapView mapView;
    private BaiduMap baiduMap;
    private BaiDuMapUtils bdUtils;
    private HistoryDao historyDao;
    private ArrayList<History> list;
    private HistoryAdapter adapter;
    private GridView gridView;
    private History history ;
    //public String title1,title2,title3,content1,content2,content3;

    public static MainRecommendFragment getInstance(String type) {

        Bundle bundle = new Bundle();
        bundle.putString("type",type);
        MainRecommendFragment fragment = new MainRecommendFragment();
        fragment.setArguments(bundle);
        return fragment;
    }
    /**
     *  生命周期方法
     * @param savedInstanceState
     */
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bitmaps = new ArrayList<>();//初始化集合
        data = new ListData(getActivity());
        arr = getActivity().getResources().getStringArray(R.array.banner);
        mData = new Data();
        items = new ArrayList<>();
        holidays = new ArrayList<>();
        zhuangtis = new ArrayList<>();
        intent = new Intent(getActivity(), Banner1Activity.class);
        list = new ArrayList<>();
        adapter = new HistoryAdapter(getActivity(),list);

        gvAdapter = new GvCityAdapter(getActivity(),holidays);
        lvRecAdapter = new LvRecAdapter(getActivity(),items);
        lvLocalAdapter = new LvLocalAdapter(getActivity(),zhuangtis);
        history = new History();
        historyDao = GreenDaoManager.getInstance(getActivity()).getNewSession().getHistoryDao();




//        title3 = "当地专题";
//       content3 = "新鲜玩法 独家推荐 精选游记";
    }


    /**
     * 初始化布局
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        itemTopBinding = DataBindingUtil.inflate(inflater,R.layout.recommendfragment_item_top,container,false);
//        itemTopRecBinding = DataBindingUtil.inflate(inflater,R.layout.recommendfragment_item_top_rec,container,false);
//        itemTopLocalBinding = DataBindingUtil.inflate(inflater,R.layout.recommendfragment_item_top_local,container,false);
//
//        tv_1 = itemTopBinding.tvTop1City;
//        tv_2=itemTopBinding.tvContent1City;
//        tv_3 = itemTopRecBinding.tvTop3Rec;
//        tv_4=itemTopRecBinding.tvContent3Rec;
//        tv_5 = itemTopLocalBinding.tvTop2Rec;
//        tv_6=itemTopLocalBinding.tvContent2Rec;
//        City city = new City();
//                    city.title = MainActivity.title2;
//                    city.content = MainActivity.content2;
//                    itemTopRecBinding.setData(city);

        //DataBinding加载布局
        rfl = DataBindingUtil.inflate(inflater,R.layout.recommendfragment_layout,container,false);
        ly = rfl.lyRec;
        mapView = rfl.mapBaidu;
        mapView.showZoomControls(false);
        baiduMap = mapView.getMap();
        bdUtils = new BaiDuMapUtils(getActivity().getApplicationContext(),baiduMap);

        gridView = rfl.gvHistory;
        gridView.setAdapter(adapter);
        loadDBData();
        //实例化轮播控件
        mCb = rfl.cb;
        //设置监听
        mCb.setOnItemClickListener(this);
        //设置控件大小
        setSize();
        sc = rfl.sc;
        sc.smoothScrollTo(0,0);

        lv_rec = rfl.lvRec;
        lv_local = rfl.lvLocalRec;
        gv = rfl.gvRec;

        lv_rec.addHeaderView(inflater.inflate(R.layout.recommendfragment_item_top_rec,null));
        lv_local.addHeaderView(inflater.inflate(R.layout.recommendfragment_item_top_local,null));

        lv_rec.setAdapter(lvRecAdapter);
        lv_local.setAdapter(lvLocalAdapter);
        gv.setAdapter(gvAdapter);
        setOnItemListener();
        MainActivity.handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what == 0x1011) {
                    ImageLoad();
                }
                //人气推荐
                if(msg.what == 0x1012){
                    //Log.e("data",data.items.size()+"");
                    if(data.items.size()>3) {
                        for (int i = 0; i < 3; i++) {
                            items.add(data.items.get(i));
                        }
                    }
                    lvRecAdapter.notifyDataSetChanged();
//                    City city = new City();
//                    city.title = MainActivity.title2;
//                    city.content = MainActivity.content2;
//                    itemTopRecBinding.setData(city);
//                    itemTopRecBinding.notifyPropertyChanged(R.id.tv_top_3_rec);
//                    itemTopRecBinding.notifyPropertyChanged(R.id.tv_content_3_rec);

                    ListViewUtils.setListViewHeightBasedOnChildren(lv_rec);

                }
                //热门城市
                if(msg.what == 0x1013) {
                    for (int i = 0; i < data.holidays.size(); i++) {
                        holidays.add(data.holidays.get(i));
                    }
                    gvAdapter.notifyDataSetChanged();
//                    tv_1.setText(MainActivity.title1);
//                    tv_2.setText(MainActivity.content1);
//                    title1 = MainActivity.title1;
//                    title2 = MainActivity.content1;
//                    itemTopBinding.notifyPropertyChanged(R.id.tv_top_1_city);
//                    itemTopBinding.notifyPropertyChanged(R.id.tv_content_1_city);
                    //Log.e("data","数据"+MainActivity.title1);
                    ListViewUtils.calGridViewWidthAndHeigh(3,gv);
                }
                //本地专题
                if(msg.what == 0x1014) {
                    for (int i = 0; i < data.zhuantis.size(); i++) {
                        zhuangtis.add(data.zhuantis.get(i));
                    }
                    lvLocalAdapter.notifyDataSetChanged();
//                    title3 = "当地专题";
//                    content3 = "新鲜玩法 独家推荐 精选游记";
//                    itemTopLocalBinding.notifyPropertyChanged(R.id.tv_top_2_rec);
//                    itemTopLocalBinding.notifyPropertyChanged(R.id.tv_content_2_rec);
                    ListViewUtils.setListViewHeightBasedOnChildren(lv_local);
                }

            }

        };
        rfl.setMyClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(getActivity(), SearchActivity.class),333);
            }
        });

        MainActivity.handler1 = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                //tv_1.setText("43434343434343434");
                //Log.e("data","Handler1====");
            }
        };
        return rfl.getRoot();
    }

    private void loadDBData(){
        list.clear();
        int size = historyDao.loadAll().size();
        if(size>4) {
            for (int i = size - 1; i >= size-5; i--) {
                list.add(historyDao.loadAll().get(i));
            }
        }else if(size <= 4){
            for (int i = size - 1; i >= 0; i--) {
                list.add(historyDao.loadAll().get(i));
            }
        }
        adapter.notifyDataSetChanged();
    }



    /**
     * 设置控件大小
     */
    private void setSize() {
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mCb.getLayoutParams();
        layoutParams.height = ScreenUtils.getScreenHeight(getActivity())/3;
        layoutParams.width  = ScreenUtils.getScreenWidth(getActivity());
        mCb.setLayoutParams(layoutParams);
    }

    /**
     * 设置轮播资源
     */
    public void ImageLoad(){
        for (int i = 0; i < data.banners.size(); i++) {
            Glide.with(this).load(data.banners.get(i).getSrc()).asBitmap().
                    into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            bitmaps.add(resource);
                            mCb.setCanLoop(false);
                            imageCarousel = new ImageCarousel(mCb, bitmaps);
                            mCb.setCanLoop(true);
                        }
                    });
        }

    }

    /**
     * 设置ListView与GridView监听
     */
    private void setOnItemListener(){
        lv_rec.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int mPosition = position-1;
                if(mPosition>-1) {
                    intent.putExtra("Link", data.items.get(mPosition).getUrl());
                    intent.putExtra("Flag", "Rec");
                    intent.putExtra("title", data.items.get(mPosition).getTitle());
                    startActivityForResult(intent, 100);
                }else {
                    intent.putExtra("Link", ContentURLs.store);
                    intent.putExtra("Flag", "store");
                    intent.putExtra("title", "服务");
                    startActivityForResult(intent, 100);
                }
            }
        });
        lv_local.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int mPosition = position-1;
                if(mPosition>-1) {
                    intent.putExtra("Link", data.zhuantis.get(mPosition).getLink());
                    intent.putExtra("Flag", "Local");
                    intent.putExtra("title", data.zhuantis.get(mPosition).getTitle());
                    startActivityForResult(intent, 100);
                }else{

                }
            }
        });

        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //插入之前判断是否存在
                int count = 0;
                for (int i = 0; i < historyDao.loadAll().size(); i++) {
//                    Log.e("data","====="+data.holidays.get(position).getTitle()+"\n");
//                    Log.e("data","++++++"+historyDao.loadAll().get(i).getName()+"\n");
                    if (data.holidays.get(position).getTitle().equals(historyDao.loadAll().get(i).getName())) {
                        count+=1;
                        Log.e("data","count===="+count+"\n");
                    }
                }
               // Log.e("data","count"+count+"\n");
                if(count==0) {
                    History history = new History(data.holidays.get(position).getTitle(),
                            data.holidays.get(position).getLink());
                    historyDao.insert(history);
                }else{
                    //Toast.makeText(mActivity, "已经存在", Toast.LENGTH_SHORT).show();
                }
                loadDBData();
            }
        });

        ly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.handler2.sendEmptyMessage(0x111);
            }
        });

    }


    @Override
    public void onItemClick(int position) {
        //Log.e("data",position+"");
        intent.putExtra("Link", data.banners.get(position).getLink());
        intent.putExtra("Flag", "Banner");
        intent.putExtra("title", arr[position]);
        startActivityForResult(intent, 100);
    }

//    @Override
//    public void onCreate(@Nullable Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        bitmaps = new ArrayList<>();
//    }

//    @Nullable
//    @Override
//    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        rfl = DataBindingUtil.inflate(inflater,R.layout.recommendfragment_layout,container,false);
//        mCb = rfl.cb;
//        ImageLoad();
//        return rfl.getRoot();
//    }

//    private void ImageLoad(){
//        bitmaps.add(BitmapFactory.decodeResource(getActivity().getResources(),R.drawable.iv_a));
//        bitmaps.add(BitmapFactory.decodeResource(getActivity().getResources(),R.drawable.iv_b));
//        bitmaps.add(BitmapFactory.decodeResource(getActivity().getResources(),R.drawable.iv_c));
//        bitmaps.add(BitmapFactory.decodeResource(getActivity().getResources(),R.drawable.iv_d));
//        bitmaps.add(BitmapFactory.decodeResource(getActivity().getResources(),R.drawable.iv_e));
//        imageCarousel = new ImageCarousel(mCb,bitmaps);
//
//    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
        mCb.startTurning(2000);//设置开始轮播以及轮播时间
        mCb.startTurning(2000);//设置开始轮播以及轮播时间

    }

    @Override
    public void onPause() {
        if(mCb!=null){
            mCb.stopTurning();//停止轮播
        }
        super.onPause();
        mapView.onPause();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mapView.onDestroy();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
//
//
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if(requestCode == 100&&resultCode == 200){
//            MainActivity.amb.rg.setVisibility(View.VISIBLE);
//        }
//    }
}



